package com.mindtree.vi.presentation.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.transaction.Synchronization;
import javax.transaction.TransactionManager;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class ViTXFilter implements Filter {

	private static JtaTransactionManager transactionManager;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	class Synchronizer implements Synchronization {

		public void afterCompletion(int arg0) {
			System.out.println("DONOTHING!!! afterCompletion");
		}

		public void beforeCompletion() {
			
		}

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		TransactionDefinition txDef = new DefaultTransactionDefinition(
				TransactionDefinition.PROPAGATION_REQUIRED);
		transactionManager = getTransactionManager(request);
		boolean exceptionRaised = false;
		TransactionStatus status = transactionManager.getTransaction(txDef);
		PlatformTransactionManager txManager = transactionManager;
		try {
			chain.doFilter(request, response);
		} catch (Exception exception) {
			exceptionRaised = true;
		} finally {
			try {
				if (exceptionRaised) {
					txManager.rollback(status);
				} else {
					txManager.commit(status);
				}
			} catch (Exception e) {
				System.out.println("TROUBLE ROLLING BACK OR COMMITTING!!!");
			}
		}
	}

	public JtaTransactionManager getTransactionManager(ServletRequest request) {
		if (transactionManager == null) {
			transactionManager = new JtaTransactionManager();
		}
		return transactionManager;
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
